<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { getClusterGroupConfigsApi, setClusterGroupConfigsApi } from '@/api/configs/clusterConfig';

const configGroupName = "database";

// 定义数据库配置类型
interface DatabaseConfigModel {
  dbType: string; // 数据库类型
  externalIp: string; // IP地址
  internalIp: string; // IP地址
  port: string; // 端口
  username: string; // 用户名
  password: string; // 密码
  dbName: string; // 数据库名
  charset: string; // 数据库编码
}

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();

// 初始化表单数据
const formData = reactive<{
  clusterId: number;
  groupName: string;
  config: DatabaseConfigModel;
  updatedAt: string;
}>({
  clusterId: 0,
  groupName: configGroupName,
  config: {
    dbType: 'mysql',
    externalIp: '',
    internalIp: '',
    port: '3306',
    username: '',
    password: '',
    dbName: '',
    charset: 'utf8mb4'
  },
  updatedAt: ''
});

// 初始化数据
onMounted(() => {
  const clusterId = route.query.clusterId;
  if (clusterId) {
    formData.clusterId = Number(clusterId);
    // 获取数据库配置
    getClusterGroupConfigsApi({
      clusterId: formData.clusterId,
      groupName: formData.groupName
    }).then(res => {
      if (res.code === 0 && res.data?.configs) {
        formData.updatedAt = res.data.updatedAt || '';
        try {
          // 解析配置数据
          const configMap: Record<string, string> = {};
          res.data.configs.forEach(item => {
            configMap[item.configKey] = item.configValue;
          });

          // 填充表单数据
          formData.config = {
            dbType: configMap.dbType, // 固定为mysql
            externalIp: configMap.externalIp || '',
            internalIp: configMap.internalIp || '',
            port: configMap.port || '3306',
            username: configMap.username || '',
            password: configMap.password || '',
            dbName: configMap.dbName || '',
            charset: configMap.charset // 固定编码
          };
        } catch (e) {
          console.error('解析数据库配置失败', e);
        }
      }
    });
  }
});

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    const submitData = {
      clusterId: formData.clusterId,
      groupName: formData.groupName,
      configs: [
        { configKey: 'dbType', configValue: formData.config.dbType, configDesc: '数据库类型' },
        { configKey: 'externalIp', configValue: formData.config.externalIp, configDesc: '数据库公网IP地址' },
        { configKey: 'internalIp', configValue: formData.config.internalIp, configDesc: '数据库内网IP地址' },
        { configKey: 'port', configValue: formData.config.port, configDesc: '数据库端口' },
        { configKey: 'username', configValue: formData.config.username, configDesc: '数据库用户名' },
        { configKey: 'password', configValue: formData.config.password, configDesc: '数据库密码' },
        { configKey: 'dbName', configValue: formData.config.dbName, configDesc: '数据库名' },
        { configKey: 'charset', configValue: formData.config.charset, configDesc: '数据库编码' }
      ]
    };

    ElMessageBox.confirm(
      '确定要保存数据库服务器配置吗？',
      '确认提交',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    ).then(async () => {
      await setClusterGroupConfigsApi(submitData);
      ElMessage.success('保存成功');
    }).catch(() => ElMessage.info('已取消保存'));
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};
</script>

<template>
  <el-form ref="formRef" :model="formData" label-width="160px" class="form-container">
    <el-form-item label="集群ID" prop="clusterId" v-if="formData.clusterId">
      <el-input v-model="formData.clusterId" disabled />
    </el-form-item>
    <el-form-item label="配置组名" prop="groupName">
      <el-input v-model="formData.groupName" disabled />
    </el-form-item>

    <el-form-item label="数据库类型" prop="config.dbType">
      <el-select v-model="formData.config.dbType" disabled placeholder="请选择数据库类型">
        <el-option label="MySQL" value="mysql" />
      </el-select>
    </el-form-item>

    <el-form-item
      label="数据库内网IP"
      prop="config.internalIp"
      :rules="[
        { required: true, message: '请输入数据库内网IP', trigger: 'blur' },
        { pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/, message: '请输入正确的IP地址', trigger: 'blur' }
      ]"
    >
      <el-input v-model="formData.config.internalIp" placeholder="请输入数据库内网IP地址" />
    </el-form-item>

    <el-form-item
      label="数据库公网IP"
      prop="config.externalIp"
      :rules="[
        { required: true, message: '请输入数据库公网IP', trigger: 'blur' },
        { pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/, message: '请输入正确的IP地址', trigger: 'blur' }
      ]"
    >
      <el-input v-model="formData.config.externalIp" placeholder="请输入数据库公网IP地址" />
    </el-form-item>

    <el-form-item
      label="数据库端口"
      prop="config.port"
      :rules="[
        { required: true, message: '请输入数据库端口', trigger: 'blur' },
        { pattern: /^\d+$/, message: '端口必须为数字', trigger: 'blur' },
        { min: 1, max: 65535, message: '端口范围应在1-65535之间', trigger: 'blur' }
      ]"
    >
      <el-input v-model.number="formData.config.port" placeholder="请输入数据库端口" />
    </el-form-item>

    <el-form-item
      label="用户名"
      prop="config.username"
      :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
    >
      <el-input v-model="formData.config.username" placeholder="请输入数据库用户名" />
    </el-form-item>

    <el-form-item
      label="密码"
      prop="config.password"
      :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
    >
      <el-input v-model="formData.config.password" type="password" placeholder="请输入数据库密码" />
    </el-form-item>

    <el-form-item
      label="数据库名"
      prop="config.dbName"
      :rules="[
        { required: true, message: '请输入数据库名', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_]+$/, message: '数据库名只能包含字母、数字和下划线', trigger: 'blur' }
      ]"
    >
      <el-input v-model="formData.config.dbName" placeholder="请输入数据库名" />
    </el-form-item>

    <el-form-item label="数据库编码" prop="config.charset">
      <el-select v-model="formData.config.charset" disabled placeholder="请选择数据库编码">
        <el-option label="utf8mb4" value="utf8mb4" />
      </el-select>
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item label="更新时间" >
      <el-input v-model="formData.updatedAt" disabled placeholder="暂无更新时间" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container { max-width: 800px; margin: 20px auto; padding: 20px; }
.form-actions { display: flex; justify-content: center; gap: 10px; margin-top: 30px; }
</style>
